package core

import (
	"context"
	"encoding/json"
	"ez/apps/core/auto/mc"
	"gitee.com/dreamwood/ez-go/db/mgo"
	"gitee.com/dreamwood/ez-go/ez"
	"gitee.com/dreamwood/ez-go/ss"
	"time"
)

type Page struct {
	mgo.BaseDoc `bson:"-" json:"-"`
	Id          int64      `json:"id" bson:"id,omitempty"`
	App         string     `json:"app" bson:"app"`     //应用
	Name        string     `json:"name" bson:"name"`   //名称
	Key         string     `json:"key" bson:"key"`     //KEY
	Route       string     `json:"route" bson:"route"` //前端页面
	Db          string     `json:"db" bson:"db"`       //数据模型
	CreateAt    time.Time  `json:"createAt" bson:"createAt"`
	UpdateAt    time.Time  `json:"updateAt" bson:"updateAt"`
	DeleteAt    *time.Time `json:"deleteAt" bson:"deleteAt"`
}

func (this *Page) DocName() string { return "Page" }
func (this *Page) GetId() int64    { return this.Id }
func (this *Page) SetId(id int64)  { this.Id = id }
func (this *Page) Create() error {
	return this.GetFactory().Create(this)
}
func (this *Page) Replace() error {
	return this.GetFactory().Replace(this)
}
func (this *Page) Save() error {
	if this.Id == 0 {
		this.CreateAt = time.Now()
		this.UpdateAt = time.Now()
		return this.GetFactory().Create(this)
	} else {
		this.UpdateAt = time.Now()
		return this.GetFactory().Replace(this)
	}
}

// 伪删除
func (this *Page) Delete() error {
	return this.GetFactory().Delete(this)
}
func (this *Page) UnDelete() error {
	return this.GetFactory().UnDelete(this)
}

// 真删除
func (this *Page) Destroy() error {
	return this.GetFactory().Destroy(this)
}
func (this *Page) ToString() string {
	return string(this.ToBytes())
}
func (this *Page) ToBytes() []byte {
	data, e := json.Marshal(this)
	ez.Try(e)
	return data
}
func (this *Page) Serialize() []byte {
	data, e := json.Marshal(this)
	ez.Try(e)
	return data
}
func (this *Page) UnSerialize(data []byte) []byte {
	ez.Try(json.Unmarshal(data, this))
	return data
}
func (this *Page) ClearRelationsBeforeSave() mgo.Doc {
	return this
}
func neverUsed_Page() {
	//导入ss包
	a := ss.M{}
	ez.Debug(a)
}

type PageAccessControl struct {
	Access  bool
	Message string
	Action  string //控制器Action,小写开头，如c,u,r,d
	Model   *Page
	Session *ez.Session
}

func NewPageAccessControl(model *Page, action string, session *ez.Session) *PageAccessControl {
	ctrl := &PageAccessControl{
		Access:  true,
		Model:   model,
		Action:  action,
		Session: session,
	}
	ez.DispatchToMany(mc.PageAccessControlEvent, ctrl, context.TODO())
	return ctrl
}
